//
//  YYStatusListViewModel.swift
//  YYWeibo
//
//  Created by strongwallyi on 16/1/3.
//  Copyright © 2016年 strongwallyi. All rights reserved.
//

import UIKit
import SDWebImage

class YYStatusListViewModel: NSObject {

    //视图模型里面引用的数据
    var statuses: [YYStatusViewModel]?
    
    func loadData(isPullUp: Bool, completion: (isSuccessed: Bool)->()){
        
        var maxId: Int64 = 0
        var sinceId: Int64 = 0
        //如果是上拉加载
        if isPullUp{
            maxId = statuses?.last?.status?.id ?? 0
            if maxId > 0 {
                maxId -= 1
            }
        }else{
            //下拉刷新
            sinceId = statuses?.first?.status?.id ?? 0
        }
        
        //定义请求地址与参数
        let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
        
        let params = ["access_token": YYUserAccountViewModel.sharedViewModel.accessToken!,
            "max_id": "\(maxId)",
            "since_id": "\(sinceId)"
        ]
        
        
        //发送网络请求
        YYNetworkTools.sharedTools.request(urlString: urlString, parameters: params) { (response, error) -> () in
            if error != nil{
                print(error)
                //请求失败,回调: 不成功
                completion(isSuccessed: false)
                return
            }
            
            guard let responseDict = response as? [String: AnyObject] else{
                completion(isSuccessed: false)
                print("返回数据不是字典")
                return
            }
            
            //字典转模型
            let statusDicts = responseDict["statuses"]! as! [[String: AnyObject]]
            
            //定义监听数据,保存转成功的模型
            var tempArray: [YYStatusViewModel] = [YYStatusViewModel]()
            
            if self.statuses == nil{
                self.statuses = [YYStatusViewModel]()
            }
            
            //遍历字典转模型
            for dict in statusDicts {
                let status = YYStatus(dict: dict)
                
                //初始化视图模型
                let statusViewModel = YYStatusViewModel()
                
                statusViewModel.status = status
                
                //把模型添加到数组里面
                tempArray.append(statusViewModel)
            }
            
            //赋值,上拉加载拼装数据
            if isPullUp{
                self.statuses! += tempArray
            }else{
                //下拉刷新数据
                self.statuses = tempArray + self.statuses!
            }
            //缓存单张图片
            self.cacheSingleImage(tempArray,completion: completion)
            
        }
    }
    
    //缓存单张图片
    private func cacheSingleImage(dataArray: [YYStatusViewModel], completion:(isSuccessed: Bool) -> ()){
        
        var dataLength = 0
        
        //创建组
        let group = dispatch_group_create()
        
        for viewModel in dataArray{
            //判断当前数组中得图片是否是单张
            if viewModel.picUrls?.count != 1{
                //不进行任何操作继续遍历
                continue
            }
            
            let urlString = viewModel.picUrls!.first!.thumbnail_pic!
            
            let url = NSURL(string: urlString)
            
            //入组
            dispatch_group_enter(group)
            
            //下载图片缓存图片
            SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
                if image != nil{
                    //计算当前图片的大小
                    dataLength += UIImagePNGRepresentation(image)!.length
                }
                //出组
                dispatch_group_leave(group)
            })
        }
        //回主线程刷新数据
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            //刷新数据
            completion(isSuccessed: true)
        }
        
    }
}
